/**
 * JoinServer
 * 
 * 28/12/2013
 * 
 * Copyright GPL
 */
package com.jtmproject;

import java.util.Set;

import com.jtmproject.bluetooth.Client;
import com.jtmproject.classes.TaskConnectWithServer;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

/**
 * This class shows a list with the servers
 * 
 * @author Javier Tejedor
 */
public class JoinServer extends Activity {

    private static final int TIME_OF_SEARCH = 6000;
	private BluetoothAdapter mBtAdapter;
    private ArrayAdapter<String> mNewDevicesArrayAdapter;
    private ArrayAdapter<String> mPairedDevicesArrayAdapter;

    /* (non-Javadoc)
     * @see android.app.Activity#onCreate(android.os.Bundle)
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
        setContentView(R.layout.activity_join_server);

        //setResult(Activity.RESULT_CANCELED);

        setListViews();
        setReceivers();
        startBluetooth();
        setPairedDevices();
        doDiscovery();
        
    }

	/**
	 * Register for broadcasts when a device is discovered
	 */
	private void setReceivers() {
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        this.registerReceiver(mReceiver, filter);

        filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        this.registerReceiver(mReceiver, filter);
	}


	/**
	 * sets the listViews (new and paired devices)
	 */
	private void setListViews() {
		mNewDevicesArrayAdapter = 
				new ArrayAdapter<String>(this, R.layout.device_name);
        mPairedDevicesArrayAdapter = 
        		new ArrayAdapter<String>(this, R.layout.device_name);
        
        ListView newDevicesListView = (ListView) findViewById(R.id.new_devices);
        newDevicesListView.setAdapter(mNewDevicesArrayAdapter);
        newDevicesListView.setOnItemClickListener(mDeviceClickListener);
        
        ListView pairedListView = (ListView) findViewById(R.id.paired_devices);
        pairedListView.setAdapter(mPairedDevicesArrayAdapter);
        pairedListView.setOnItemClickListener(mDeviceClickListener);
	}


	/**
	 * sets the paired devices
	 */
	private void setPairedDevices() {
		Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices();
        
        if (pairedDevices.size() > 0) {
            findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
            for (BluetoothDevice device : pairedDevices) {
                mPairedDevicesArrayAdapter.add(
                		device.getName() + "\n" + device.getAddress());
            }
        } else {
            String noDevices = 
            		getResources().getText(R.string.none_paired).toString();
            mPairedDevicesArrayAdapter.add(noDevices);
        }
	}
    

    /**
     * this starts the bluetooth
     */
    private void startBluetooth(){
    	mBtAdapter = BluetoothAdapter.getDefaultAdapter();

        if (mBtAdapter == null) {
        	
            Toast.makeText(
            		this, 
            		"Bluetooth is not available", 
            		Toast.LENGTH_LONG).show();
            
            this.finish();
            
        } else{
        	
        	if (!mBtAdapter.isEnabled()) {
        		mBtAdapter.enable();
        		//be careful!!
                while(mBtAdapter.isEnabled() == false){ 
                	mBtAdapter.enable();
                }
            }
        	
        }
    }
    
    /* (non-Javadoc)
     * @see android.app.Activity#onDestroy()
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (mBtAdapter != null) {
            mBtAdapter.cancelDiscovery();
        }

        //unregister broadcast listeners
        this.unregisterReceiver(mReceiver);
    }

    /**
     * Start device discover with the BluetoothAdapter
     */
    private void doDiscovery() {

        setTitle(R.string.scanning);

        findViewById(R.id.title_new_devices).setVisibility(View.VISIBLE);

        // If we're already discovering, stop it
        if (mBtAdapter.isDiscovering()) {
            mBtAdapter.cancelDiscovery();
        }

        mBtAdapter.startDiscovery();
        
        final Thread thread = new Thread() {  
			public void run() {
				try {
					sleep(TIME_OF_SEARCH);
					if(mBtAdapter.isDiscovering()){
						mBtAdapter.cancelDiscovery();
                                            }
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		};
		thread.start(); 
    }

    /**
     * The on-click listener for all devices in the ListViews
     */
    private OnItemClickListener mDeviceClickListener = 
    		new OnItemClickListener() {
        public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3){
        	
            mBtAdapter.cancelDiscovery();

            // Get the device MAC address, 
            //which is the last 17 chars in the View
            String info = ((TextView) v).getText().toString();
            String address = info.substring(info.length() - 17);

            Client client = (Client) new Client(address, mBtAdapter);
            Client.setClient(client); 
            
            new TaskConnectWithServer(JoinServer.this, client).execute();
            
        }
    };


    /**
     * The BroadcastReceiver that listens for discovered devices and
     *  changes the title when discovery is finished
     */
    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
    	
        /* (non-Javadoc)
         * @see android.content.BroadcastReceiver#onReceive(android.content.Context, android.content.Intent)
         */
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if (BluetoothDevice.ACTION_FOUND.equals(action)) {

                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

                if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
                    mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
                }

            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
            	
                setProgressBarIndeterminateVisibility(false);
                setTitle(R.string.select_device);
                
                if (mNewDevicesArrayAdapter.getCount() == 0) {
                	
                    String noDevices = getResources().getText(R.string.none_found).toString();
                    mNewDevicesArrayAdapter.add(noDevices);
                    
                }
            }
        }
    };

}
